package com.bnz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.Student;
import com.bnz.pojo.StudentExample;
import com.bnz.pojo.StudentVo;
import com.bnz.service.StudentService;
import com.bnz.util.MybatisUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentServiceImpl implements StudentService {

    //1. 列表所有学生
    @Override
    public List<Student> findAll() {
        try(SqlSession session = MybatisUtil.getSqlSession()){
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            List<Student> students = mapper.selectByExample(null);
            return students;
        }
    }

    //2. 查询单个学生
    @Override
    public Student findById(int i) {
        try(SqlSession session = MybatisUtil.getSqlSession()){
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            Student student = mapper.selectByPrimaryKey(i);
            return student;
        }
    }

    @Override
    public void insert(Student student) {
        try(SqlSession session = MybatisUtil.getSqlSession()){
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            mapper.insert(student);
        }
    }

    //4. 条件查询带分页
//4. 条件查询带分页
    @Override
    public PageResult<Student> search(int page, int pagesize, StudentVo vo) {
        PageHelper.startPage(page,pagesize);

        //4.1 进行实例查询
        if(vo != null){
            try(SqlSession session = MybatisUtil.getSqlSession()){
                //4.1.1 得到StudentMapper对象
                StudentMapper mapper = session.getMapper(StudentMapper.class);
                //4.1.2 得到查询实例
                StudentExample example = new StudentExample();
                //4.1.3 得到查询条件
                StudentExample.Criteria criteria = example.createCriteria();
                //4.1.4 封装查询条件
                if(StrUtil.isNotBlank(vo.getSname())){
                    criteria.andSnameLike("%" + vo.getSname() + "%");
                }
                if(StrUtil.isNotBlank(vo.getAddr())){
                    criteria.andAddrLike("%" + vo.getAddr() + "%");
                }
                if(vo.getCid() != 0){
                    criteria.andCidEqualTo(vo.getCid());
                }
                //4.1.5 开始条件查询
                List<Student> students = mapper.selectByExample(example);
                //4.1.6 转换为Page对象
                Page<Student> studentPage = (Page<Student>) students;
                //4.1.7 返回
                return new PageResult<>(studentPage.getPages(),studentPage.getResult());
            }

        }
        return null;
    }

}
